//
//  DataSummaryVC.swift
//  TimeBoat
//
//  Created by bo wang on 2022/8/24.
//  Copyright © 2022 Time Boat. All rights reserved.
//

import UIKit
import MJRefresh
import SafariServices

class DataSummaryVC: AppBaseVC {
    
    weak static var shared: DataSummaryVC?
    
    private var cellVMs : [[DataSummaryCellViewModel]]?
    
    @IBOutlet var titleView: DataSummaryTitleView!
    @IBOutlet var collectionView: UICollectionView!
    @IBOutlet var flowlayout: UICollectionViewFlowLayout!
    
    private var data: SummaryDataModel?
    private var adList: [SummaryADDataModel] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !APP.tuic{
            self.cellVMs = [[ DataSummaryCellViewModel(.sportRing),
                              DataSummaryCellViewModel(.sleep),
                              DataSummaryCellViewModel(.temperature),
                              DataSummaryCellViewModel(.sport),
                              DataSummaryCellViewModel(.location)]]
        }else{
            self.cellVMs = [[ DataSummaryCellViewModel(.sportRing),
                              DataSummaryCellViewModel(.heartRate),
                              DataSummaryCellViewModel(.sleep),
                              DataSummaryCellViewModel(.temperature),
                              DataSummaryCellViewModel(.bloodPressure),
                              DataSummaryCellViewModel(.bloodOxygen),
                              DataSummaryCellViewModel(.sport),
                              DataSummaryCellViewModel(.location)]]
        }

        
        Self.shared = self
        if #available(iOS 14, *) {
            navigationItem.backButtonDisplayMode = .minimal
        }
        navigationItem.backButtonTitle = ""
        
        view.layoutIfNeeded()
        collectionView.contentInset.top = titleView.bounds.height - STATUS_BAR_HEIGHT
        collectionView.enableRefresh(callback: self, header: true, footer: false)
        reloadDataAndUI()
        
        NotificationCenter.default.addObserver(self, selector: #selector(onUserLoginDidChanged(_:)), name: .userDidLogin, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(onUserLoginDidChanged(_:)), name: .userDidLogout, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(onUserLoginDidChanged(_:)), name: .userDeviceListUpdate, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(onUserLoginDidChanged(_:)), name: .userDeviceListClear, object: nil)
        NotificationCenter.default.addObserverBTLEDidConnectedPeripheral(observer: self, selector: #selector(onBTLEConnected), object: nil)
        NotificationCenter.default.addObserverBTLEDidDisconnectPeripheral(observer: self, selector: #selector(onBTLEDisconnected), object: nil)
        NotificationCenter.default.addObserverBTLEDidUpdateData(observer: self, selector: #selector(onDidUpdateData), object: nil)
        
        collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: R.reuseIdentifier.dataSummaryFooter.identifier)
        collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: R.reuseIdentifier.dataSummaryHeader.identifier)
    }
  
    @objc func onDidUpdateData(_ noti: Notification) {
        reqData()
    }
    
    @objc func onUserLoginDidChanged(_ noti: Notification) {
        reloadDataAndUI()
    }
    
    @objc func onBTLEConnected() {
        self.titleView.stateLabel.text = "智能手表连接成功"
        reloadDataAndUI()
    }
    
    @objc func onBTLEDisconnected() {
        self.titleView.stateLabel.text = "智能手表未连接..."
        reloadDataAndUI()
    }
    
    func vm(at indexPath: IndexPath) -> DataSummaryCellViewModel {
        (self.cellVMs?[indexPath.section][indexPath.item])!
    }
    
    private func reloadDataAndUI() {
        if AccountManager.shareAccount().didLogined() {
            collectionView.refreshHeader?.beginRefreshing()
        } else {
            data = nil
            collectionView.endRefreshing()
            collectionView.reloadData()
        }
        
        reqADData()
    }
    
    private func reqData() {
        let uuid = AccountManager.shareAccount().loginModel.userUUID
        let imei = AccountManager.shareAccount().deviceImei()
        if (uuid.count > 0 && imei.count > 0) {
            API.getHomeData(uuid: uuid, imei: imei) { [weak self] result in
                guard let data = result.data else {
                    if AccountManager.shareAccount().didLogined() {
                        HUD.showFail(msg: result.errDesc)
                    }
                    self?.collectionView.endRefreshing()
                    return
                }
                self?.data = data
                self?.collectionView.reloadSections(IndexSet(integer: 0))
                self?.collectionView.endRefreshing()
            }
        } else {
            self.collectionView.endRefreshing()
        }
    }
    
    func reqADData() {
        API.getHomeADData { [weak self] result in
            guard let list = result.dataList else { return }
            if (self?.cellVMs?.count ?? 0) < 2 {return}
            self?.adList = list
            self?.cellVMs?[1] = list.map({ _ in DataSummaryCellViewModel(.ad) })
            self?.collectionView.reloadSections(IndexSet(integer: 1))
        }
    }
    
}

extension DataSummaryVC: RefreshProtocol {
    func onRefreshing(_ component: MJRefreshComponent, isLoadMore: Bool) {
        reqData()
        
        BTLESendDataManager.shared.sendSyncTimeCMD()
    }
}

extension DataSummaryVC:  UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return self.cellVMs?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.cellVMs?[section].count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let vm = vm(at: indexPath)
        let cell = vm.cell(for: collectionView, indexPath: indexPath)
        
        if indexPath.section == 1 {
            cell.update(vm: vm, data: adList[indexPath.item])
        } else {
            cell.update(vm: vm, data: data)
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let vm = vm(at: indexPath)
        return vm.itemSize(for: flowlayout)
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionFooter {
            //            return collectionView.dequeueReusableCell(withReuseIdentifier: R.reuseIdentifier.dataSummaryFooter, for: indexPath) as! UICollectionReusableView
            //            return collectionView.dequeueFooter(R.reuseIdentifier.dataSummaryFooter, for: indexPath)
            
            return  collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier:R.reuseIdentifier.dataSummaryFooter.identifier, for: indexPath)
        }
        //        let header = collectionView.dequeueHeader(R.reuseIdentifier.dataSummaryHeader, for: indexPath)
        //        let header =  collectionView.dequeueReusableCell(withReuseIdentifier: R.reuseIdentifier.dataSummaryHeader, for: indexPath) as! UICollectionReusableView
        let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier:R.reuseIdentifier.dataSummaryHeader.identifier, for: indexPath)
        
        header.isHidden = indexPath.section == 0
        return header
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return section == 0 ? CGSize.zero : flowlayout.headerReferenceSize
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let vm = vm(at: indexPath)
        
        if let chartSubject = vm.subject.chartSubject {
            showChart(subject: chartSubject)
        } else if vm.subject == .ad {
            /// 暂时不做跳转
            //            let ad = adList[indexPath.item]
            /// TODO: 网页链接？
            //            openWebpage(ad.adUrl)
        }
    }
}

extension DataSummaryVC {
    func showChart(subject: ChartsSubject) {
        let navi = navigationController
        AccountManager.loginIfNeed(self) { didLogined, model in
            if didLogined {
                let vc = R.storyboard.charts.chartsVC()!
                vc.subject = subject
                navi?.pushViewController(vc, animated: true)
            }
        }
    }
    
    func openWebpage(_ urlStr: String?) {
        guard let urlStr = urlStr,
              let url = URL(string: urlStr) else { return }
        let vc = SFSafariViewController(url: url)
        present(vc, animated: true)
    }
}
